package com.uni.action;

import com.uni.entity.User;
import com.uni.service.Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/18 13:58
 * ------------------------------------------
 */
@WebServlet(name = "UserLoginServlet", urlPatterns = "/toLogin")
public class UserLoginAction extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        int ck = Integer.parseInt(req.getParameter("ck"));
        Integer answer = (Integer)session.getAttribute("answer");
        boolean isRemember = req.getParameter("re").equals("true");
        User user = Service.user.checkUser(username, password);
        if(user == null){
            resp.getWriter().write("账号密码有误");
        } else if(ck != answer){
            resp.getWriter().write("验证码错误");
        } else{

            // 登录成功 就创建Cookie对象
            Cookie cname = new Cookie("username", username);
            Cookie cpw = new Cookie("password", password);
            req.getSession().setAttribute("username", username);
            if(isRemember) {
                // 设置Cookie的有效时长 7天
                cname.setMaxAge(3600 * 24 * 7);
                cpw.setMaxAge(3600 * 24 * 7);
                // 设置Cookie路径
                cname.setPath(req.getContextPath());
                cpw.setPath(req.getContextPath());
                // 写入客户端
                resp.addCookie(cname);
                resp.addCookie(cpw);
            }
            /* 保存用户信息到 session域 */
            req.getSession().setAttribute("userInfo", user);
            resp.getWriter().write("true");
        }
    }

}
